<template>
    <view class="page">

        <!--<template v-if="up_id">-->
            <u-notice-bar text="您将向公寓房东在线交租，请确认租约信息无误。如有疑问请致电客服!"></u-notice-bar>
            <view class="profile">
                <view class="info">
                    <u-avatar icon="order" fontSize="32" bg-color="#c0c4cc" size="50"></u-avatar>
                    <view class="cbox" style="margin-left: 30rpx">
                        <u-text :text="title" bold size="16"></u-text>
                        <u-text :text="rent_money + '元/月'" size="12" margin="10rpx 0 0 0"></u-text>
                    </view>
                </view>
                <view class="tel" @click="goMyLease">
                    <u-text text="其他租约" size="14" margin="0 10rpx"></u-text>
                    <u-icon :customStyle="{paddingLeft:1+'rpx'}" name="arrow-right" size="18"></u-icon>
                </view>
            </view>
            <u-sticky bgColor="#fff">
                <u-tabs :list="list" :current="current" lineWidth="60" lineColor="#f56c6c" :activeStyle="{color: '#303133',}" @change="ChangeHandler"></u-tabs>
            </u-sticky>

            <view class="content">
                <template v-for="(item,index) in bill">
                    <view class="_titme">{{item.pay_date}}</view>
                    <view class="bill-card" @click.stop.prevent="setSelect(index)">
                        <view style="flex: 1">
                            <he-radio :is-change="false" v-model="item.is_selected"></he-radio>
                        </view>
                        <view style="display:flex;flex-direction: column;flex: 9; margin-top: 20rpx">
                            <view style="display:flex; justify-content: space-between">
                                <view style="font-size: 14px;">
                                    <text>￥{{item.money}}</text>
                                    <text style="margin-left: 10rpx;">{{item.msg}}</text>
                                </view>
                                <view>
                                    <text v-if="item.pay_status===0" style="color: #ffaa00;">未支付</text>
                                    <text v-if="item.pay_status===1" style="color: #ffaa00;">已支付</text>
                                    <text style="margin-left: 10rpx; color: #ffaa00;">({{item.pay_date}}到期)</text>
                                </view>
                            </view>

                            <view style="display:flex; justify-content: space-between; font-size: 11px; margin: 20rpx 0">
                                <text>{{item.r_time_start}}至{{item.r_time_end}}</text>
                                <text>{{item.pay_date}}前</text>
                            </view>
                        </view>
                    </view>

                    <template v-for="(value,key) in item.other_expenses">
                        <view class="bill-card" @click.stop.prevent="setSelect(index,key)">
                            <view style="flex: 1">
                                <he-radio :is-change="false" v-model="value.is_selected"></he-radio>
                            </view>
                            <view style="display:flex;flex-direction: column;flex: 9; margin-top: 20rpx">
                                <view style="display:flex; justify-content: space-between">
                                    <view style="font-size: 14px;">
                                        <text>￥{{value.money}}</text>
                                        <text style="margin-left: 10rpx;">{{value.s_name}}</text>
                                    </view>
                                    <view>
                                        <text v-if="item.pay_status===0" style="color: #ffaa00;">未支付</text>
                                        <text v-if="item.pay_status===1" style="color: #ffaa00;">已支付</text>
                                        <text style="margin-left: 10rpx; color: #ffaa00;">({{item.pay_date}}到期)</text>
                                    </view>
                                </view>

                                <view style="display:flex; justify-content: space-between; font-size: 11px; margin: 20rpx 0">
                                    <text>{{item.r_time_start}}至{{item.r_time_end}}</text>
                                    <text>{{item.pay_date}}前</text>
                                </view>
                            </view>
                        </view>
                    </template>
                    <view class="bill-card" style="justify-content: space-between" v-if="index === 0" @click="selectCoupon">
                        <view>
                            <u-text prefixIcon="red-packet-fill" iconStyle="font-size: 50rpx;color: #E60B30"
                                     bold block	size="35rpx" text="红包/抵用券"></u-text>
                        </view>
                        <view>
                            <u-text suffixIcon="arrow-right" iconStyle="font-size: 16px;" size="14px"
                                    :text="coupon_tips"></u-text>
                        </view>
                    </view>
                </template>

                <u-gap height="50"></u-gap>
                <view class="safe-area-inset-bottom"></view>
            </view>

            <view class="he-settlement">
                <view class="footer">
                    <view class="info">
                        <view style="display: flex;align-items: center" @click.stop="setAll">
                            <he-radio :is-change="false" v-model="all"></he-radio>
                            <view class="he-select__all" style="font-weight: bold">全选</view>
                        </view>
                        <view class="cbox" style="margin-left: 10rpx">
                            <text class="he-select__all">共选中{{radio}}条账单</text>
                            <view>
                                <text class="he-select__all">合计 </text>
                                <text style="font-size: 14px; color: #f56c6c;font-weight: bold">￥ {{money}}</text>
                            </view>
                            <!--<u-text text="用户251租房偏好租房偏2" bold size="16"></u-text>-->
                            <!--<u-text text="550元/月" size="12" margin="10rpx 0 0 0"></u-text>-->
                        </view>
                    </view>
                    <view style="width: 150rpx">
                        <u-button type="warning" text="支付" @click="pay"></u-button>
                    </view>
                </view>
                <view class="safe-area-inset-bottom"></view>
            </view>
        <!--</template>-->

        <!--<template v-else>-->
            <!--<u-empty mode="favor" text="还没有选择签约" textSize="18" iconSize="100"></u-empty>-->
            <!--<view style="margin: 60rpx">-->
                <!--<u-button type="primary" text="查看我的签约" @click="toIndexPage"></u-button>-->
            <!--</view>-->
        <!--</template>-->
    </view>
</template>

<script>
    import heRadio from "../../../components/he-radio.vue";
    export default {
        components:{
            heRadio
        },
        data() {
            return {
                current: 0,
                update: true,
                list: [{
                    name: '未支付',
                    type: 0
                }, {
                    name: '已支付',
                    type: 1
                }],
                bill:[],
                all: false,
                up_id:'',
                page: {
                    count: 1,
                    size: 10,
                    current: 1,
                },
                radio: 0,
                money: 0,

                title:'',
                rent_money:'',

                coupons:[],
                coupon_tips:'',
                coupon_id:'',
            };
        },
        onLoad(option){
            let u_id = uni.getStorageSync('u_id');
            let userInfo = uni.getStorageSync('userInfo');

            if (u_id && userInfo.mobile) {
                if (JSON.stringify(option) === '{}') {   // 这里直接进支付房租页面，默认取租约的第一条来展示
                    let params = {u_id: u_id, tel: userInfo.mobile, p: this.page.current};
                    uni.showLoading({title: '正在加载'});
                    uni.$u.http.get('/api.php/UserClinet/my_contract' + uni.$u.queryParams(params),).then(res => {
                        uni.hideLoading();
                        this.up_id = res.data[0].id;
                        this.title = res.data[0].title;
                        this.rent_money = res.data[0].rent_money;
                        let params = {
                            u_id: uni.getStorageSync('u_id'),
                            up_id: res.data[0].id,
                            p: this.page.current,
                            pay_status: this.list[this.current].type
                        };
                        this.getPaymentList(params);
                    });
                }else {
                    this.up_id = option.id;
                    this.title = option.title;
                    this.rent_money = option.rent_money;

                    let params = {
                        u_id: uni.getStorageSync('u_id'),
                        up_id: option.id,
                        p: this.page.current,
                        pay_status: this.list[this.current].type
                    };
                    this.getPaymentList(params);
                }
            }else{
                uni.navigateTo({url:'/pages/user/my/login'});
            }
        },
        onReachBottom() {
            if (this.page.count > this.page.current * this.page.size ) {
                let params = {
                    u_id: uni.getStorageSync('u_id'),
                    up_id: this.up_id,
                    p: this.page.current++,
                    pay_status: this.list[this.current].type
                };
                this.getPaymentList(params,true);
            }
        },
        methods: {
            ChangeHandler(e){
                // uni.showLoading({title: '正在加载'});
                this.current = e.index;

                let params = {
                    u_id: uni.getStorageSync('u_id'),
                    up_id: this.up_id,
                    p: this.page.current,
                    pay_status: this.list[this.current].type
                };
                this.getPaymentList(params);

                // 刷新组件
                this.reload();
            },

            reload() {
                // 移除组件
                this.update = false;
                // 在组件移除后，重新渲染组件
                // this.$nextTick可实现在DOM 状态更新后，执行传入的方法。
                this.$nextTick(() => {
                    this.update = true
                })
            },
            setSelect(index,key){
                if (key === undefined) {
                    this.bill[index].is_selected = !this.bill[index].is_selected;
                }else{
                    this.bill[index].other_expenses[key].is_selected = !this.bill[index].other_expenses[key].is_selected;
                }

                this.calcRadioCount();
            },
            setAll(){
                this.all = !this.all;
                for (let i = 0; i < this.bill.length; i++) {
                    this.bill[i].is_selected = this.all;
                    for (let j = 0; j < this.bill[i].other_expenses.length; j++) {
                        this.bill[i].other_expenses[j].is_selected = this.all;
                    }
                }
                this.calcRadioCount();
            },
            calcRadioCount(){
                let count = 0;
                let money = 0;
                for (let i = 0; i < this.bill.length; i++) {
                    if (this.bill[i].is_selected) {
                        count ++;
                        money+= parseInt(this.bill[i].money);
                    }
                    for (let j = 0; j < this.bill[i].other_expenses.length; j++) {
                        if (this.bill[i].other_expenses[j].is_selected) {
                            count ++;
                            money+= parseInt(this.bill[i].other_expenses[j].money);
                        }
                    }
                }

                this.radio = count;
                // 计算选中的金额
                this.money = money;
            },

            pay(){
                //  拿到所有选中的id
                let array = [];
                let h_id = '';
                for (let i = 0; i < this.bill.length; i++) {
                    if (this.bill[i].is_selected) {
                        array.push(this.bill[i].id);
                        h_id = this.bill[i].h_id;
                    }
                    for (let j = 0; j < this.bill[i].other_expenses.length; j++) {
                         if (this.bill[i].other_expenses[j].is_selected) {
                             array.push(this.bill[i].other_expenses[j].id);
                         }
                    }
                }

                let parmas = {
                    b_ids: array.join(),
                    u_id: uni.getStorageSync('u_id'),
                    h_id: h_id,
                    c_id: this.coupon_id
                };

                uni.showLoading({title: '正在等待'});
                uni.$u.http.post('/api.php/Pay/pay_do', parmas).then(res => {
                    uni.hideLoading();
                    if (res === '') {
                        console.log(res);
                        return;
                    }else{
                        let payment ={
                            provider: 'wxpay',
                            orderInfo:'测试信息',
                            appId: res.appId,
                            timeStamp: res.timeStamp,
                            nonceStr: res.nonceStr,
                            package: res.package,
                            signType: res.signType,
                            paySign: res.paySign,
                            success:function () {
                                uni.showToast({
                                    title: '支付成功', //提示文字
                                    duration: 2000, //显示时长
                                    icon: "success", //图标，支持"success"、"loading"
                                });
                            },
                            fail:function () {
                                uni.showToast({
                                    title: '支付失败',
                                    duration: 2000,
                                    icon: "error",
                                });
                            }
                        };
                        uni.requestPayment(payment);
                    }
                });
            },

            goMyLease(){
                uni.redirectTo({url: '/pages/user/my/lease'});
            },

            getPaymentList(params, append = false) {
                uni.showLoading({title: '正在加载'});
                uni.$u.http.get('/api.php/UserClinet/my_pay_house' + uni.$u.queryParams(params),).then(res => {
                    uni.hideLoading();
                    let data = uni.$u.deepClone(res.data);
                    for (let i = 0; i < data.length; i++) {
                        data[i].is_selected = false;
                        for (let j = 0; j < data[i].other_expenses.length; j++) {
                            data[i].other_expenses[j].is_selected = false;
                        }
                        if (parseInt(data[i].is_coupon) === 1){
                            this.coupons = data[i].coupon_list;
                            let canUse = 0;
                            for (let j = 0; j < data[i].coupon_list[j].length; j++) {
                                if ( data[i].coupon_list[j].disable === 0){
                                    canUse++;
                                }
                            }
                            this.coupon_tips = canUse + '个代金券可用';
                        } else {
                            this.coupon_tips = '无可用代金券';
                        }
                    }

                    if (append) {
                        for (let i = 0; i < data.length; i++) {
                            this.list.push(data[i]);
                        }
                    }else{
                        this.bill = data;
                    }

                    this.page.count = res.total;
                    this.page.size = res.per_page;
                    this.page.current = res.current_page;
                });
            },

            selectCoupon(){
                if (this.coupons.count < 0) return;
                uni.$once('coupon',(data)=>{
                    this.coupon_id = data.coupon_id;
                    let day = 0;
                    for (let i = 0; i < this.coupons.length; i++) {
                        if (this.coupons[i].id === data.coupon_id) {
                            day = this.coupons[i].c_time;
                        }
                    }
                    this.coupon_tips = '已选择1张，可减' + day +'天';
                });

                uni.navigateTo({url: '/pages/user/active/select' + uni.$u.queryParams({'coupon_list': this.coupons})});
            },
        }
    }
</script>

<style lang="scss" scoped>

    .page {
        width: 100%;
        min-height: 100vh;
        background-color: RGBA(245, 245, 245, 1);
        /*background-color: #f3f4f6;*/
    }
    .content{
        padding: 20rpx 10rpx;
    }

    .profile{
        @include flex(row);
        justify-content: space-between;
        padding: 20rpx;
        background-color: #ffffff;
    }

    .info{
        @include flex(row);
        justify-content: flex-start;
        align-items: center;
        flex: 9;
        margin-right: 20rpx;
    }
    .cbox{
        @include flex(column);
    }
    .tel{
        @include flex(row);
        justify-content: flex-start;
        flex: 3;
    }

    .bill-card{
        display: flex;
        align-items: center;
        background-color: white;
        padding: 20rpx;
        border-radius: 15px;
        margin-bottom: 20rpx;

        ._bottom{
            font-size: 12px;
            color: #C0C0C0;
        }
    }

    .he-settlement {
        position: fixed;
        bottom: var(--window-bottom);
        width: 100%;
        min-height: 96px;
        background: #FFFFFF;
        z-index: 2;
        border-top: 1rpx solid #c0c4cc;
    }
    .he-select__all {
        font-size: 30rpx;
        font-family: PingFang SC;
        font-weight: 400;
        color: #222222;
        margin-left: 16rpx;
    }

    .footer{
        @include flex(row);
        justify-content: space-between;
        padding: 20rpx 20rpx 0 20rpx;
    }
</style>
